//
//  MFWVersionUtils.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-7-23.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "MFWVersionUtils.h"

@implementation MFWVersionUtils

/**
 获取app版本号
 1. 优先取 CFBundleShortVersionString
 2. 如果步骤1没有取到则取 CFBundleVersion
 */
+ (NSString*)appVersion;
{
    NSString * version = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    if (version == nil || [version length] == 0)
    {
        version = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
    }
    
    return version;
}


/**
 * AppStore中使用的version
 * CFBundleShortVersionString
 */
+ (NSString*)markingVersion;
{
    return [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

/**
 * CFBundleVersion
 */
+ (NSString*)technicalVersion;
{
    return [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
}

/**
 * 版本号比较
 */
+ (NSComparisonResult)compareOldVersion:(NSString*)oldVersion toNewVersion:(NSString*)newVersion;
{
    NSArray* oldComponents = [[oldVersion stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsSeparatedByString:@"."];
    NSArray* newComponents = [[newVersion stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsSeparatedByString:@"."];
    
    NSUInteger oldComponentsCount = [oldComponents count];
    NSUInteger newComponentsCount = [newComponents count];
    
    NSUInteger count = MAX(oldComponentsCount, newComponentsCount);
    
    for (NSUInteger i = 0; i < count; i++)
    {
        int new = i < newComponentsCount ? [[newComponents objectAtIndex:i] intValue] : 0;
        int old = i < oldComponentsCount ? [[oldComponents objectAtIndex:i] intValue] : 0;
        
        if (new > old)
        {
            return NSOrderedAscending;
        }
        else if (new < old)
        {
            return NSOrderedDescending;
        }
    }
    
    
    return NSOrderedSame;
}

@end
